from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet
from labor_price.models import Department,Position
import json
from rest_framework.decorators import action
from rest_framework.response import Response
class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model=Department
        fields='__all__'

class DepartmentView(ModelViewSet):
    queryset = Department.objects.all()  # 查询集
    serializer_class = DepartmentSerializer  # 序列化器

    """
    depart_role:
    获取部门下的角色
    """

    @action(methods=['get'], detail=False)
    def batch_del(self, request):
        del_list = request.GET.get('del_list')
        del_list = json.loads(del_list)
        try:
            for i in (del_list):
                Department.objects.get(id=i).delete()
        except:
            return Response({'msg': "批量删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return Response({'msg': "批量删除成功", 'code': 200})

    #  获取部门下的职位
    @action(methods=['get'], detail=False)
    def depart_role(self, request):
        depart_id = request.GET.get('depart_id')
        data=[]
        depart_role = Position.objects.filter( department_id = int(depart_id))
        for i in depart_role:
            obj = {
                "name":"",
                "id":None,
            }
            obj['id'] = i.id
            obj['name'] = i.jobName
            data.append(obj)
        return Response({'msg': data, 'code': 200})